<template>
  <div  class='login_box'>
      <h1  class='mb28'>晚峰后台管理系统</h1>
      <a-tabs defaultActiveKey="1" >
        <a-tab-pane tab="账号登录" key="1">
            <a-form
          id="components-form-demo-normal-login"
          :form="form"
          class="login-form"
          @submit="handleSubmit"
        >
          <a-form-item>
            <a-input
              v-decorator="[
                'loginName',
                { rules: [{ required: true, message: '请输入用户名!' }] }
              ]"
              placeholder="用户名"  size='large'
            >
              <a-icon
                slot="prefix"
                type="user"
                style="color: rgba(0,0,0,.25)"
              />
            </a-input>
          </a-form-item>
          <a-form-item>
            <a-input
              v-decorator="[
                'password',
                { rules: [{ required: true, message: '请输入密码!' }] }
              ]"
              type="password"
              placeholder="密码"  size='large'
            >
              <a-icon
                slot="prefix"
                type="lock"
                style="color: rgba(0,0,0,.25)"
              />
            </a-input>
          </a-form-item>
          <a-form-item>
            <a-button  :loading='btnLoading'
              type="primary"
              html-type="submit"
              class="login-form-button"
              size='large' 
            >
              登录
            </a-button>
          </a-form-item>
        </a-form>
        </a-tab-pane>
      </a-tabs>
  </div>
</template>

<script>
  import { login }  from  '@/api/login/index'
export default {
  name: 'login',
  data () {
    return {
      btnLoading:false,/*登录按钮等待加载*/
    }
  },
  beforeCreate () {
    this.form = this.$form.createForm(this);
  },
  methods:{
    handleSubmit (e) {
      e.preventDefault();
      this.form.validateFields((err, values) => {
        if (!err) {
          // console.log('Received values of form: ', values);
          this.btnLoading = true
          login(values).then((response)=>{
                  let that = this
                  this.$message.success('登录成功')

                  //把返回token存储 - sessionStorage
                  sessionStorage.setItem('token', response.data.token)
                  sessionStorage.setItem('routers', JSON.stringify(response.data.routers))
                  sessionStorage.setItem('currentUser', JSON.stringify({
                      name      : response.data.username 
                  }))
                  sessionStorage.setItem('tokenId', response.data.tokenId)

                  //把返回token存储 - vuex  /**vuex响应所有用到这个数据的组件  sessStorage 存不动值**/
                  that.$store.commit("setusername",response.data.username);
                  that.$store.commit("setcacheRoute",['product','property']);

                  /*初始化首页路由*/
                  // this.initIndexRouter()
                  let redirect = decodeURIComponent(
                      this.$route.query.redirect || "/home/tendency"
                  ) 
                  this.$router.push(redirect); 

                  this.btnLoading = false
          })
          .catch(error=>{//catch(error) response执行有错误
              // console.log(error.config) 
              // console.log(error.code) 
              // console.log(error.message) 
              // console.log(error.response) 
              // this.$message.error(error.response.data)  //统一写到response的error捕捉里
              this.btnLoading = false
          })
        }
      });
    },
    /*初始化首页路由*/
    initIndexRouter(){
        let indexRouter = {
          path: '/',
          name: "homeIndex",
          component:()=>import('@/views/home/index'),
          children: [
            ...this.generateChildRouters()
          ]
        }
        this.$router.addRoutes([indexRouter])
    },
    /*生成嵌套路由（子路由）*/
    generateChildRouters(){
        let that = this
        //如果还没有存在 需要返回一个空对象，否则会报错 Cannot convert undefined or null to object 因为children数组中存的值不能为undefined
        if (!window.sessionStorage.getItem('routers')) {
            return {}
        }

        let routers = JSON.parse(sessionStorage.getItem('routers')) 
        /*子路由数组，最后由函数return*/
        let childRouters = []
        /*左侧菜单*/
        let items = [] 

        for(let router of routers) {
            try { 
              /*路由存储*/
              if(router.isRouter == '1'  ){  
                  // let index_props = 'views/homework/index'  //将路径拆解成 '@/' + ... 这样才能正确解析
                  let childRouter = {
                      path: JSON.parse(router.routerCode).path,
                      name: JSON.parse(router.routerCode).name,
                      component:resolve => require(['@/' + JSON.parse(router.routerCode).component.slice(2)], resolve),   
                      meta:JSON.parse(router.routerCode).meta
                  } 
                  childRouters.push(childRouter) 
              }
              /*左侧菜单存储*/
              if(router.isMenu == '1'){ 
                  /*一级目录*/
                  if(router.parentId == 1){
                      let item = {
                        id: router.id,
                        parentId:router.parentId,
                        name: router.name,
                        icon:router.icon,
                        to: JSON.parse(router.routerCode).path,
                        sort:router.sort,
                      }
                      items.push(item)
                  } 
              } 
            }
            catch (ex) {
                console.warn(ex.message)
            }
        }
         
        this.treeLeftNavChild(items,routers)/*二级菜单*/
        /*菜单排序*/
        function sortBy(a,b){
          return  a.sort - b.sort
        }
        let menu = items.sort(sortBy)
        this.$store.commit("setmenudata",menu); 
       
        return childRouters
    },
    treeLeftNavChild(arr,routers){
        arr.forEach((item)=>{
            let child= []
            routers.forEach((it)=>{
              if(it.isMenu == '1'){
                if(item.id == it.parentId){ 

                    child.push({
                      id:it.id,
                      parentId:it.parentId,
                      name:it.name,
                      icon:it.icon,
                      to: JSON.parse(it.routerCode).path
                    })
                }
              }
            })
            if(child.length!=0){
              item.children=child
            }
          })
    },
    
  },
  computed:{
    
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
  .login_box{width: 400px;margin:0 auto;padding-top: 120px;}
#components-form-demo-normal-login .login-form {
  max-width: 300px;
}
#components-form-demo-normal-login .login-form-forgot {
  float: right;
}
#components-form-demo-normal-login .login-form-button {
  width: 100%;
}
</style>
